import React, { useState, useEffect } from 'react';
import { Button, Dialog, Message } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import cls from 'classnames';
import CreateProjectModal from 'components/createProjectModal/loadable';
import ImportProjectModal from 'components/importProjectModal/loadable';
import exceed from 'utils/apimap';
import utils from 'utils';
import { getFeature } from 'utils/features';
import { CSSTransition } from 'react-transition-group';
import track from 'utils/track';
import { navigateOpen } from 'utils/router';
import { uilessRequest } from '@alife/yunxiao-common';
import moment from 'moment';
import './index.scss';
import intl from '../../locale';

const { organization_id, user_role } = window.FORCE.organization;
const isOrgOwner = user_role === 'ORG_OWNER';

const defaultCardList = isOrgOwner
  ? [
      {
        text: intl.get({
          id: 'code-assets.components.newbieTask.AddCodeLibrary',
          defaultMessage: '添加代码库',
        }),
        complete_text: intl.get({
          id: 'code-assets.components.newbieTask.AddedCodeLibrary',
          defaultMessage: '&#128079已完成代码库添加',
        }),
        type: 'add_repository',
        status: 'unfinished',
        style: { backgroundImage: 'linear-gradient(174deg, #72C9FF 0%, #CCECFE 100%)' },
        complete_style: { backgroundImage: 'linear-gradient(-32deg, #91E0BA 0%, #7DD4AB 99%)' },
      },

      {
        text: intl.get({
          id: 'code-assets.components.newbieTask.SubmitCode',
          defaultMessage: '提交代码',
        }),
        complete_text: intl.get({
          id: 'code-assets.components.newbieTask.CodeSubmissionCompleted',
          defaultMessage: '&#128079已完成代码提交',
        }),
        description: intl.get({
          id: 'code-assets.components.newbieTask.ModifyAndSubmitTheCode',
          defaultMessage: '1.在页面直接修改和提交代码<br />2.或克隆库到本地提交',
        }),
        type: 'push_commit',
        status: 'unfinished',
        style: { backgroundImage: 'linear-gradient(174deg, #72C9FF 0%, #CCECFE 100%)' },
        complete_style: { backgroundImage: 'linear-gradient(-32deg, #91E0BA 0%, #7DD4AB 99%)' },
      },

      {
        text: intl.get({
          id: 'code-assets.components.newbieTask.InviteEnterpriseMembers',
          defaultMessage: '邀请企业成员',
        }),
        complete_text: intl.get({
          id: 'code-assets.components.newbieTask.MemberInvitationCompleted',
          defaultMessage: '&#128079已完成成员邀请',
        }),
        type: 'invite_organization_member',
        status: 'unfinished',
        style: { backgroundImage: 'linear-gradient(174deg, #72C9FF 0%, #CCECFE 100%)' },
        complete_style: { backgroundImage: 'linear-gradient(-32deg, #91E0BA 0%, #7DD4AB 99%)' },
      },
    ]
  : [
      {
        text: intl.get({
          id: 'code-assets.components.newbieTask.AddCodeLibrary',
          defaultMessage: '添加代码库',
        }),
        complete_text: intl.get({
          id: 'code-assets.components.newbieTask.AddedCodeLibrary',
          defaultMessage: '&#128079已完成代码库添加',
        }),
        type: 'add_repository',
        status: 'unfinished',
        style: { backgroundImage: 'linear-gradient(174deg, #72C9FF 0%, #CCECFE 100%)' },
        complete_style: { backgroundImage: 'linear-gradient(-32deg, #91E0BA 0%, #7DD4AB 99%)' },
      },

      {
        text: intl.get({
          id: 'code-assets.components.newbieTask.SubmitCode',
          defaultMessage: '提交代码',
        }),
        complete_text: intl.get({
          id: 'code-assets.components.newbieTask.CodeSubmissionCompleted',
          defaultMessage: '&#128079已完成代码提交',
        }),
        description: intl.get({
          id: 'code-assets.components.newbieTask.ModifyAndSubmitTheCode',
          defaultMessage: '1.在页面直接修改和提交代码<br />2.或克隆库到本地提交',
        }),
        type: 'push_commit',
        status: 'unfinished',
        style: { backgroundImage: 'linear-gradient(174deg, #72C9FF 0%, #CCECFE 100%)' },
        complete_style: { backgroundImage: 'linear-gradient(-32deg, #91E0BA 0%, #7DD4AB 99%)' },
      },
    ];

const { setCache, getCache } = utils;

const prefix = 'codeup-newbie-task';
const NewbieTask = ({
  onChangeNewbieTaskVisible,
  onAllTasksFinished,
  pushCommit,
  createRepository,
  importRepository,
  onCloseNewbieTask,
  onExpandStatusChange,
  welcomeDialogStatus,
}) => {
  const cacheExpand = getCache('codeup-newbie-task-expand', false);
  const [cardList, setCardList] = useState(
    getCache('codeup-newbie-task-card-list') || defaultCardList,
  );
  const [expand, setExpand] = useState(cacheExpand ? JSON.parse(cacheExpand) : false);
  const [repositoryTask, setRepositoryTask] = useState(
    getCache('codeup-newbie-task-add_repository'),
  );
  const [taskNumber, setTaskNumber] = useState(getCache('codeup-newbie-task-number') || 0);
  const [showAddRepo, setShowAddRepo] = useState(false);
  const [showPushDesc, setShowPushDesc] = useState(false);
  const [showCreateProjectModal, setShowCreateProjectModal] = useState(false);
  const [showImportProjectModal, setShowImportProjectModal] = useState(false);
  const [addRepository, setAddRepository] = useState(false);
  const [gitPushCommit, setGitPushCommit] = useState(false);
  const [newbieTaskSum] = useState(isOrgOwner ? 3 : 2);
  const [gotWelfareReward, setGotWelfareReward] = useState(null);
  const [inviteMemberInterval, setInviteMemberInterval] = useState(null);
  const [showCloseTask, setShowCloseTask] = useState(false);
  const [showWelfareDetail, setShowWelfareDetail] = useState(false);
  const [qrCode, setQrCode] = useState('');
  const [isFeitianVip, setIsFeitianVip] = useState(false);

  useEffect(() => {
    const isStickcache = window.TB_NAVIGATION.isSidebarStick;
    const task = document.querySelector('.codeup-newbie-task');
    if (task) {
      getSmallMicroDingTalkQRCode();
      if (isStickcache === 'false' || isStickcache === false) {
        task.style.width = 'calc(100% - 64px)';
      } else {
        task.style.width = 'calc(100% - 220px)';
      }
    }
    if (!getCache('codeup-newbie-task-card-list')) {
      setCache('codeup-newbie-task-card-list', cardList);
    }
  }, []);

  useEffect(() => {
    return () => {
      // unmount
      if (inviteMemberInterval) {
        clearInterval(inviteMemberInterval);
      }
    };
  }, [inviteMemberInterval]);

  const fetchGotBaseResource = () => {
    if (!getFeature('new_bie_task.fetch.base.resource')) {
      return;
    }
    Promise.all([
      uilessRequest({
        url: `/api/ajax/org/tbs/org/v2/organizations/${organization_id}/orders?orderFrom=commonbuy`,
        method: 'GET',
      }),

      uilessRequest(`/api/ajax/org/tbs/org/v2/organizations/${organization_id}/plan`),
    ])
      .then(([res, { data }]) => {
        const hasBaseResourcePackage = res.data?.find(
          (order) => order.planName === 'baseResource' && moment(order.endDate).isAfter(moment()),
        );
        if (hasBaseResourcePackage || data.type !== 'baseVersion') {
          setGotWelfareReward(true);
        } else {
          setGotWelfareReward(false);
        }
      })
      .catch(() => {
        setGotWelfareReward(null);
      });
  };

  useEffect(() => {
    // 查询创建代码库任务是否完成
    if (!isTaskFinished('add_repository')) {
      getUserActivities('init');
    }

    // 推送commit任务是否完成
    if (!isTaskFinished('push_commit')) {
      getUserActivities('push');
    }

    // 查询邀请企业成员任务是否已完成，未完成并且任务已经处于开始状态（根据缓存判断）则轮询
    if (!isTaskFinished('invite_organization_member') && isOrgOwner) {
      const taskStatus = getCache(`codeup-newbie-task-invite-${organization_id}-status`, false);
      // 任务未完成，创建定时器轮询
      if ((taskStatus && taskStatus === 'start') || !taskStatus) {
        // 任务开始时的企业成员数量
        let startNumber = getCache(`codeup-newbie-task-invite-${organization_id}-current`, false);
        const membersInterval = setInterval(() => {
          getOrganizationMemberInfo((nowMembers) => {
            if (!startNumber) {
              setCache(
                `codeup-newbie-task-invite-${organization_id}-current`,
                nowMembers.length,
                false,
              );
              startNumber = nowMembers.length;
            }

            if (nowMembers && nowMembers.length > startNumber) {
              onChangeCardStatus('invite_organization_member', { status: 'complete' }, true);
              onChangeTaskNumber(Number(getCache('codeup-newbie-task-number')) + 1);
              setCache(`codeup-newbie-task-invite-${organization_id}-status`, 'finished', false);
              clearInterval(membersInterval);
            }
          });
        }, 10000);
        setInviteMemberInterval(membersInterval);
        setTimeout(() => {
          if (membersInterval) {
            clearInterval(membersInterval);
          }
        }, 1000 * 60 * 5);
      } else if (taskStatus === 'finished') {
        onChangeCardStatus('invite_organization_member', { status: 'complete' });
        onChangeTaskNumber(taskNumber + 1);
      }
    }
    fetchGotBaseResource();
  }, []);

  useEffect(() => {
    if (addRepository) {
      onChangeAddRepositoryTask(true);
    }
  }, [addRepository]);

  useEffect(() => {
    if (gitPushCommit) {
      onChangePushCommitTask(true);
    }
  }, [gitPushCommit]);

  useEffect(() => {
    if (pushCommit) {
      setShowPushDesc(false);
      onChangePushCommitTask(true);
    }
  }, [pushCommit]);

  useEffect(() => {
    if (createRepository) {
      onChangeAddRepositoryTask(true);
    }
  }, [createRepository]);

  useEffect(() => {
    if (importRepository) {
      getUserActivities('init');
    }
  }, [importRepository]);

  useEffect(() => {
    if (Number(taskNumber) >= newbieTaskSum) {
      finishAllTasks();
    }
  }, [taskNumber]);

  useEffect(() => {
    if (!welcomeDialogStatus) {
      if (localStorage.getItem('codeup-newbie-task-expand') === null) {
        setTimeout(() => {
          setExpand(true);
          setCache('codeup-newbie-task-expand', true);
          onExpandStatusChange(true);
        }, 100);
      }
    }
  }, [welcomeDialogStatus]);

  const getSmallMicroDingTalkQRCode = () => {
    exceed
      .fetch({
        api: 'newbieTask.qrcode',
      })
      .then((res) => {
        try {
          setQrCode(JSON.parse(res.result).smallMicroDingTalkQRCode);
        } catch (error) {
          console.log(error);
        }
      });
  };
  useEffect(() => {
    fetch(
      `https://${
        location.href.includes('pre-') ? 'pre-b' : 'bridge'
      }.aliyun.com/abs/onlineBizBenefitManager/aliyunVipValid?appName=yunxiao`,
      { credentials: 'include' },
    )
      .then((res) => res.json())
      .then(({ success, data }) => {
        if (!success || data.role !== 'vip' || `${data.status}` !== '0') return;
        setIsFeitianVip(true);
      });
  }, []);

  const getUserActivities = (type) => {
    exceed
      .forceFetch({
        api: 'users.activities',
        data: {
          event_filter: type,
        },
      })
      .then((result) => {
        if (type === 'init') {
          if (result.amount === 1 && result.list[0].dataMap[':name'] === 'Codeup-Demo') {
            setAddRepository(false);
          } else {
            setAddRepository(result.amount > 0);
          }
        } else if (type === 'push') {
          setGitPushCommit(result.amount > 0);
        }
      });
  };

  const onChangeExpandStatus = () => {
    if (expand) {
      // 即将收起
      track({
        action: 'shrink newbie task',
        page: 'new member page',
        control: 'newbie task',
      });
    } else {
      //  即将展开
      track({
        action: 'expand newbie task',
        page: 'new member page',
        control: 'newbie task',
      });
    }
    setExpand(!expand);
    setCache('codeup-newbie-task-expand', !expand);
    onExpandStatusChange(!expand);
  };

  const onChangeCardList = (list) => {
    setCardList(list);
    setCache('codeup-newbie-task-card-list', list);
  };

  const onChangeCardStatus = (type, item = {}, useCache = false) => {
    let tmpCardList = cardList;
    if (useCache) {
      tmpCardList = getCache('codeup-newbie-task-card-list');
    }
    const list = tmpCardList.map(({ type: innerType, ...others }) => {
      if (type === innerType) {
        return { type: innerType, ...others, ...item };
      }
      return { type: innerType, ...others };
    });
    onChangeCardList(list);
  };

  const onChangeTaskNumber = (number) => {
    setTaskNumber(number);
    setCache('codeup-newbie-task-number', number);
  };

  const onChangeMemberTask = () => {
    if (isTaskFinished('invite_organization_member')) {
      return;
    }
    const nextUrl = encodeURIComponent(`${location.origin}?org_id=${organization_id}`);
    navigateOpen(
      `https://devops.aliyun.com/org-admin/${organization_id}/members/member?invite=true&next_url=${nextUrl}`,
      '_blank',
    );
  };

  const isTaskFinished = (type) => {
    let hasFinish = true;
    cardList.forEach(({ type: innerType, status }) => {
      if (innerType === type) {
        hasFinish = status === 'complete';
      }
    });
    return hasFinish;
  };

  const onChangeAddRepositoryTask = (finish = false) => {
    if (isTaskFinished('add_repository')) {
      // 如果已经完成任务，再次调用这个函数直接返回
      return;
    }

    if (!finish) {
      setShowAddRepo(true);
    } else {
      setRepositoryTask(true);
      onChangeCardStatus('add_repository', { status: 'complete' });
      setCache('codeup-newbie-task-add_repository', repositoryTask);
      onChangeTaskNumber(taskNumber + 1);
    }
  };

  const onChangePushCommitTask = (finish = false) => {
    if (isTaskFinished('push_commit')) {
      // 如果已经完成任务，再次调用这个函数直接返回
      return;
    }
    if (!finish) {
      setShowPushDesc(true);
    } else {
      onChangeCardStatus('push_commit', { status: 'complete' });
      setCache('codeup-newbie-task-push_commit', true);
      onChangeTaskNumber(taskNumber + 1);
    }
  };

  const taskComplete = (type) => {
    const list = cardList.filter(({ type: innerType }) => {
      return innerType !== type;
    });
    onChangeCardList(list);
  };

  const handelTaskClick = (type) => {
    if (type === 'invite_organization_member') {
      track({
        action: 'invite member',
        page: 'home page',
        type: '',
        control: 'newbie task',
      });

      onChangeMemberTask();
    }

    if (type === 'add_repository') {
      track({
        action: 'go_to_new_repo',
        page: 'home page',
        type: '',
        control: 'newbie task',
      });

      onChangeAddRepositoryTask();
    }

    if (type === 'push_commit') {
      track({
        action: 'commit',
        page: 'home page',
        type: '',
        control: 'newbie task',
      });

      onChangePushCommitTask();
    }
  };

  const getOrganizationMemberInfo = (success) => {
    exceed
      .forceFetch({
        api: 'organization.member',
        params: {
          orgId: organization_id,
        },
      })
      .then((result) => {
        success(result.result);
      })
      .catch((err) => {
        console.log(err);
      });
  };

  const createRepositoryModalOpen = () => {
    track({
      action: 'new_repo',
      page: 'home page',
      type: '',
      control: 'newbie task',
    });

    setShowCreateProjectModal(true);
  };

  const importRepositoryModalOpen = () => {
    track({
      action: 'import_repo',
      page: 'home page',
      type: '',
      control: 'newbie task',
    });

    setShowImportProjectModal(true);
  };

  const renderAddRepository = () => {
    return (
      <div className={`${prefix}__content__card__add_repo`}>
        <Button
          className={`${prefix}__content__card__add_repo--import`}
          onClick={() => {
            importRepositoryModalOpen();
          }}
        >
          {intl.get({ id: 'code-assets.components.newbieTask.Import', defaultMessage: '导入' })}
        </Button>
        <div className={`${prefix}__content__card__add_repo--divide`} />
        <Button
          className={`${prefix}__content__card__add_repo--create`}
          onClick={() => {
            createRepositoryModalOpen();
          }}
        >
          {intl.get({ id: 'code-assets.components.newbieTask.New', defaultMessage: '新建' })}
        </Button>
      </div>
    );
  };

  const handleDescClicked = (type) => {
    if (type === 'push_commit') {
      setShowPushDesc(false);
    }
  };

  const renderNormalDesc = (type, description) => {
    return (
      <div className={`${prefix}__content__card desc`} onClick={() => handleDescClicked(type)}>
        <span
          dangerouslySetInnerHTML={{ __html: description }}
          className={`${prefix}__content__card--desc_text`}
        />
      </div>
    );
  };

  const renderNormalTask = (
    text,
    complete_text,
    type,
    status,
    style,
    complete_style,
    description,
  ) => {
    if (type === 'push_commit' && showPushDesc) {
      return <React.Fragment>{renderNormalDesc(type, description)}</React.Fragment>;
    }

    // 通用task
    return (
      <React.Fragment>
        <div
          className={`${prefix}__content__card`}
          style={status === 'complete' ? { ...complete_style } : { ...style }}
          key={type}
        >
          <span
            className={`${prefix}__content__card--text`}
            dangerouslySetInnerHTML={{ __html: status === 'complete' ? complete_text : text }}
          />

          {status === 'unfinished' && (
            <React.Fragment>
              {type === 'add_repository' && showAddRepo ? (
                renderAddRepository()
              ) : (
                <Button
                  type="primary"
                  className={`${prefix}__content__card--btn`}
                  onClick={() => handelTaskClick(type)}
                >
                  {intl.get({
                    id: 'code-assets.components.newbieTask.Complete',
                    defaultMessage: '去完成',
                  })}
                </Button>
              )}
            </React.Fragment>
          )}

          {status === 'complete' && (
            <Button
              type="normal"
              className={`${prefix}__content__card--btn complete`}
              onClick={() => taskComplete(type)}
            >
              {intl.get({
                id: 'code-assets.components.newbieTask.GotIt',
                defaultMessage: '知道了',
              })}
            </Button>
          )}
        </div>
      </React.Fragment>
    );
  };

  const renderTaskInDialog = (text, type, status) => {
    return (
      <div className={`${prefix}-welfare-dialog-container-content-task-item`}>
        <div className={`${prefix}-welfare-dialog-container-content-task-item-title`}>{text}</div>
        {status === 'complete' && (
          <div className={`${prefix}-welfare-dialog-container-content-task-item-btn-finished`}>
            <span className="btn-text">
              {intl.get({
                id: 'code-assets.components.newbieTask.Completed',
                defaultMessage: '已完成',
              })}
            </span>
          </div>
        )}
      </div>
    );
  };

  const getTaskCards = () => {
    return cardList.map(
      ({ text, complete_text, type, status, style, complete_style, description }) => {
        return renderNormalTask(
          text,
          complete_text,
          type,
          status,
          style,
          complete_style,
          description,
        );
      },
    );
  };

  const getTaskResources = async () => {
    const aliyun_uid =
      utils.getCookie('login_aliyunid_pk') || utils.getCookie('LOGIN_ALIYUN_PK_FOR_TB');
    const { user = {} } = window.FORCE || {};
    const { orgId } = window.UILessConfig || {};
    const response = await uilessRequest({
      method: 'POST',
      url: `/api/ajax/org/tbs/org/v2/organizations/${orgId}/orders`,
      data: {
        buyerId: Number(aliyun_uid),
        payerId: Number(aliyun_uid),
        userId: aliyun_uid,
        tbUserId: user.id,
        token: `${new Date().valueOf()}${Math.floor(Math.random() * 100)}`,
        orderId: Number(`${new Date().valueOf()}${Math.floor(Math.random() * 1000)}`),
        orgId,
        isDeleted: false,
        instanceId: `bonus_org_${Number(
          `${new Date().valueOf()}${Math.floor(Math.random() * 1000)}`,
        )}`,
        orderType: 'BUY',
        orderFrom: 'bonus',
        commodityCode: 'org',
        planType: 'bonus',
        planName: 'bonus_package',
        size: 1,
        startDate: moment().format(),
        gmtCreate: moment().format(),
        endDate: '2999-01-01T00:00:00+08:00',
        purchases: null,
      },
    });

    if (response.data.id) {
      fetchGotBaseResource();
      Dialog.confirm({
        messageProps: {
          type: 'success',
        },
        title: intl.get({
          id: 'code-assets.components.newbieTask.WelfareResourcePackageReceived',
          defaultMessage: '福利资源包已领取',
        }),
        content: (
          <div>
            代码管理：代码库数量不限，代码库容量不限（单库容量：Git 库 10GB + LFS 不限）
            <br />
            {intl.get({
              id: 'code-assets.components.newbieTask.PipelineTheMaximumNumberOf',
              defaultMessage: '流水线：最大并发任务数增加到 6，运行时长增加到 5400 分钟/月',
            })}
            <br />
            {intl.get({
              id: 'code-assets.components.newbieTask.ProductWarehouseUnlimitedCapacity',
              defaultMessage: '制品仓库：容量不限',
            })}
          </div>
        ),

        onClose: () => location.reload(),
        footer: (
          <Button type="primary" onClick={() => location.reload()}>
            {intl.get({
              id: 'code-assets.components.newbieTask.Determine',
              defaultMessage: '确定',
            })}
          </Button>
        ),
      });
    } else {
      Message.error({
        title: intl.get({
          id: 'code-assets.components.newbieTask.FailedToReceive',
          defaultMessage: '领取失败，请联系人工咨询！',
        }),
      });
    }
  };

  const finishAllTasks = () => {
    if (isOrgOwner && !gotWelfareReward) {
      if (Number(taskNumber) >= newbieTaskSum || isFeitianVip) {
        exceed.fetch({
          api: 'uiless.featureflag.put',
          data: {
            flagkey: 'xw-task-codeup',
            value: 'true',
          },
        });
      }
    }
    if (inviteMemberInterval) {
      clearInterval(inviteMemberInterval);
    }
    if ((isOrgOwner && gotWelfareReward) || !isOrgOwner) {
      // 企业管理员，并且已经是小微企业，则完成任务;或者普通成员，直接完成任务
      onChangeNewbieTaskVisible(false);
      onAllTasksFinished();
    }
  };

  const openDetailDialog = () => {
    track({
      action: 'apply-for-reward',
      page: 'new member page',
      type: '',
      control: 'newbie task',
    });

    setShowWelfareDetail(true);
  };

  const getWelfareCard = () => {
    const finished = Number(taskNumber) >= newbieTaskSum;
    // 已申请小微福利，直接完成任务
    if (gotWelfareReward && finished) {
      finishAllTasks();
      return;
    } else if (gotWelfareReward === null || gotWelfareReward) {
      return null;
    }
    track({
      action: 'enter newbie fuli task',
      page: 'home page',
      type: '',
      control: 'newbie task',
    });

    return (
      <div
        className={`${prefix}__content__card`}
        style={{
          width: '252px',
          backgroundImage:
            'url(https://img.alicdn.com/tfs/TB1_t2yJpY7gK0jSZKzXXaikpXa-660-128.png)',
          backgroundSize: '100% 100%',
          backgroundRepeat: 'no-repeat',
        }}
        onClick={() => {
          if (!finished) {
            openDetailDialog();
          }
        }}
      >
        <span
          className={`${prefix}__content__card--text`}
          // dangerouslySetInnerHTML={{ __html: '&#127873 领取 23722 元企业版套餐' }}
          // dangerouslySetInnerHTML={{ __html: `&#127873 ${isFeitianVip ? '飞天会员免费领取' : '领取 23722 元企业版套餐'}` }}
        >
          {isFeitianVip
            ? intl.get({
                id: 'code-assets.components.newbieTask.DirectResourcesForApsaraMembership',
                defaultMessage: '飞天会员直享资源',
              })
            : intl.get({
                id: 'code-assets.components.newbieTask.FreeResourcePackage',
                defaultMessage: '免费领取资源包',
              })}
        </span>
        {/* <Button
           text
           type="normal"
           className={`${prefix}__content__card--btn abandon`}
          >
           放弃
          </Button> */}
        <Button
          type="normal"
          className={cls(`${prefix}__content__card--btn welfare`)}
          onClick={(e) => {
            e.stopPropagation();
            if (finished || isFeitianVip) {
              //
              track({
                action: 'receive-for-reward',
                page: 'new member page',
                type: '',
                control: 'newbie task',
              });

              finishAllTasks();
              getTaskResources();
            } else {
              // 查看详情，打开弹窗
              openDetailDialog();
            }
          }}
        >
          {/* || isFeitianVip */}
          {/* {finished || isFeitianVip ? '0元购买' : '查看详情'} */}
          {intl.get({ id: 'code-assets.components.newbieTask.Free', defaultMessage: '免费领取' })}
        </Button>
      </div>
    );
  };

  const mouseEnterNewbieTask = () => {
    setShowCloseTask(true);
  };

  const mouseLeaveNewbieTask = () => {
    setShowCloseTask(false);
  };

  const closeNewbieTask = () => {
    track({
      action: 'close newbie task',
      page: 'new member page',
      control: 'newbie task',
    });

    onCloseNewbieTask();
    onChangeNewbieTaskVisible(false);
  };

  if (welcomeDialogStatus) {
    return null;
  }

  const finishedNewbieTask = Number(taskNumber) >= newbieTaskSum;

  return (
    <>
      <div className={cls(prefix, { closeExpand: !expand })}>
        <div onMouseEnter={mouseEnterNewbieTask} onMouseLeave={mouseLeaveNewbieTask}>
          <div
            className={cls(`${prefix}__arrows`, { arrowsOpen: !expand })}
            onClick={onChangeExpandStatus}
          >
            <YunxiaoIcon type={expand ? 'arrow-down-2-line' : 'arrow-up-2-line'} />
            {!expand && (
              <span>
                {finishedNewbieTask
                  ? intl.get({
                      id: 'code-assets.components.newbieTask.NoviceTaskCompleted',
                      defaultMessage: '新手任务已完成',
                    })
                  : intl.get(
                      {
                        id: 'code-assets.components.newbieTask.NoviceTaskTasknumberNewbietasksum',
                        defaultMessage: '新手任务 {taskNumber} / {newbieTaskSum}',
                      },
                      { taskNumber, newbieTaskSum },
                    )}
              </span>
            )}
          </div>

          {!expand && (
            <CSSTransition
              in={showCloseTask}
              timeout={500}
              classNames={finishedNewbieTask ? 'close-task-finished' : 'close-task'}
            >
              <div
                className={cls(`${prefix}__arrows-close`, {
                  show: showCloseTask,
                  finished: finishedNewbieTask && showCloseTask,
                })}
                onClick={closeNewbieTask}
              >
                <YunxiaoIcon type="false-line" style={{ color: '#8C8C8C' }} />
              </div>
            </CSSTransition>
          )}
        </div>

        {expand && (
          <section className={`${prefix}__content`}>
            {getTaskCards()}
            {isOrgOwner ? getWelfareCard() : null}
          </section>
        )}
      </div>

      {showCreateProjectModal && (
        <CreateProjectModal
          closeModal={() => {
            setShowCreateProjectModal(false);
          }}
          onCreateSuccess={() => {
            // 创建成功
            onChangeAddRepositoryTask(true);
          }}
          isModalOpen={showCreateProjectModal}
        />
      )}

      {showImportProjectModal && (
        <ImportProjectModal
          closeModal={() => {
            setShowImportProjectModal(false);
            getUserActivities('init');
          }}
          isModalOpen={showImportProjectModal}
        />
      )}

      <Dialog
        className={`${prefix}-welfare-dialog`}
        visible={showWelfareDetail}
        footer={false}
        footerActions={[]}
        onClose={() => setShowWelfareDetail(false)}
      >
        <div className={`${prefix}-welfare-dialog-container`}>
          <div className={`${prefix}-welfare-dialog-container-img`}>
            <img src="" className={`${prefix}-welfare-dialog-img`} />
            <div className={`${prefix}-welfare-dialog-container-detail`}>
              <div className={`${prefix}-welfare-dialog-container-detail-title`}>
                {intl.get({
                  id: 'code-assets.components.newbieTask.UpgradeResourcesForFree',
                  defaultMessage: '免费升级资源',
                })}
              </div>
              <div className={`${prefix}-welfare-dialog-container-detail-desc`}>
                <div className={`${prefix}-welfare-dialog-container-detail-desc-item`}>
                  <div className={`${prefix}-welfare-dialog-container-detail-desc-item-text`}>
                    代码管理：代码库数量不限，代码库容量不限（单库容量：Git 库 10GB + LFS 不限）
                  </div>
                </div>
                <div className={`${prefix}-welfare-dialog-container-detail-desc-item`}>
                  <div className={`${prefix}-welfare-dialog-container-detail-desc-item-text`}>
                    {intl.get({
                      id: 'code-assets.components.newbieTask.PipelineTheMaximumNumberOf',
                      defaultMessage: '流水线：最大并发任务数增加到 6，运行时长增加到 5400 分钟/月',
                    })}
                  </div>
                </div>
                <div className={`${prefix}-welfare-dialog-container-detail-desc-item`}>
                  <div className={`${prefix}-welfare-dialog-container-detail-desc-item-text`}>
                    {intl.get({
                      id: 'code-assets.components.newbieTask.ProductWarehouseUnlimitedCapacity',
                      defaultMessage: '制品仓库：容量不限',
                    })}
                  </div>
                </div>
                <div className={`${prefix}-welfare-dialog-container-detail-desc-item`}>
                  <img style={{ width: '40%', margin: '0 auto' }} src={qrCode} />
                </div>
                <div className={`${prefix}-welfare-dialog-container-detail-desc-item`}>
                  <div
                    style={{ margin: '0 auto' }}
                    className={`${prefix}-welfare-dialog-container-detail-desc-item-text`}
                  >
                    {intl.get({
                      id: 'code-assets.components.newbieTask.DingtalkScanTheQrCode',
                      defaultMessage: '钉钉扫码入群获取更多福利',
                    })}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className={`${prefix}-welfare-dialog-container-content`}>
            <div className={`${prefix}-welfare-dialog-container-content-title`}>
              {intl.get({
                id: 'code-assets.components.newbieTask.ApplicationProcess',
                defaultMessage: '申请流程',
              })}
            </div>
            <div className={`${prefix}-welfare-dialog-container-content-desc`}>
              {intl.get({
                id: 'code-assets.components.newbieTask.CompleteTheTaskToObtain',
                defaultMessage: '完成任务获取资源',
              })}
            </div>
            <div className={`${prefix}-welfare-dialog-container-content-task`}>
              <div className={`${prefix}-welfare-dialog-container-content-task-left`}>
                {defaultCardList.map(() => {
                  const dot = (
                    <div
                      className={`${prefix}-welfare-dialog-container-content-task-left-circle-complete`}
                    />
                  );
                  const line = (
                    <div className={`${prefix}-welfare-dialog-container-content-task-left-line`} />
                  );
                  return (
                    <React.Fragment>
                      {dot}
                      {line}
                    </React.Fragment>
                  );
                })}
                <div
                  className={`${prefix}-welfare-dialog-container-content-task-left-circle-unfinish`}
                />
              </div>
              <div>
                {defaultCardList.map(({ text, type }) => {
                  let status = 'complete';
                  cardList.forEach((card) => {
                    if (card.type === type) {
                      status = card.status;
                    }
                  });
                  return renderTaskInDialog(text, type, status);
                })}
                {renderTaskInDialog(
                  intl.get({
                    id: 'code-assets.components.newbieTask.ObtainResources',
                    defaultMessage: '获取资源',
                  }),
                  null,
                  null,
                )}
              </div>
            </div>
          </div>
        </div>
      </Dialog>
    </>
  );
};

export default NewbieTask;
